package message

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"web/userop/api"
	"web/userop/forms"
	"web/userop/global"
	"web/userop/proto"
)

// 获取用户留言列表
func GetMessageList(ctx *gin.Context) {
	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	rsp, err := global.UseropSrvClient.MessageList(context.Background(), &proto.MessageRequest{
		UserId: userId,
	})
	if err != nil {
		zap.S().Error("获取用户留言列表失败：", err)
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	var m []gin.H
	for _, v := range rsp.Data {
		m = append(m, gin.H{
			"file":     v.File,
			"id":       v.Id,
			"message:": v.Message,
			"subject":  v.Subject,
			"type":     v.MessageType,
			"user_id":  v.UserId,
		})
	}
	ctx.JSON(http.StatusOK, m)
}

// 用户添加留言
func AddMessage(ctx *gin.Context) {
	f := new(forms.MessageForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	res, err := global.UseropSrvClient.CreateMessage(context.Background(), &proto.MessageRequest{
		UserId:      userId,
		MessageType: f.MessageType,
		Subject:     f.Subject,
		Message:     f.Message,
		File:        f.File,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		zap.S().Error("添加留言信息失败：", err)
		return
	}

	ctx.JSON(http.StatusOK, res)
}
